<template>
  <el-button size="small" type="primary" @click="visible=true">
    <Icon icon="material-symbols:person-add"/>
    添加
  </el-button>
  <el-dialog title="添加用户" :width="`${width}px`" v-model:model-value="visible">
    <el-form size="small" :model="formData" :rules="rules" @submit.prevent="handleSubmit" ref="formEl">
      <el-form-item prop="username">
        <el-input placeholder="用户名" v-model:model-value="formData.username"/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input placeholder="密码" v-model:model-value="formData.password"/>
      </el-form-item>
      <el-form-item prop="email">
        <el-input placeholder="邮箱" v-model:model-value="formData.email"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="w-full" native-type="submit">添加</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup="setup">
  import {Icon} from "@iconify/vue";
  import {reactive, ref} from "vue";
  import useUser from "@/hooks/useUser";
  import {CODE_OK} from "@/api/consts";
  import {ElMessage} from "element-plus";
  import useWidth from "@/hooks/useWidth";
  const visible=ref(false);
  const formEl = ref<HTMLFormElement|null>(null);
  const {userAdd} = useUser();
  const emits = defineEmits(['refresh']);
  const {width} = useWidth(400);
  const formData = reactive({
    username:'',
    password:'',
    email:'',
  });
  const rules = {
    username:[{required:true,message:'用户名必填'}],
    password:[{required:true,message:'密码必填'}],
    email:[{required:true,message:'密邮箱填'},
      {type:'email',message:'邮箱格式不正确'}
    ],
  };
  const handleSubmit = ()=>{
    formEl.value!.validate().then(async (ok:boolean)=>{
      if(!ok) return;
      userAdd(formData).then((res)=>{
        if(res.code===CODE_OK){
          ElMessage.success(res.msg)
          emits('refresh');
          visible.value=false;
          return;
        }
        ElMessage.error(res.msg);
      }).catch((e)=>{
        ElMessage.error(e);
      });
    });
  };
</script>

<style scoped lang="scss">

</style>